<template>
    <div>
       <!-- 面包屑 -->
       <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/shouye' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图 -->
      <el-card>
          <!-- 搜索框 -->
          <el-row :gutter="20">
                <!-- layout布局的栅格 -->
                    <el-col :span="12">
                          <el-input placeholder="请输入内容" v-model="queryinfo.query" clearable @clear="getuserlist">
                          <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                      <el-button type="primary" @click="adddialog=true">用户添加</el-button>
                </el-col>
          </el-row>
          <!-- 用户列表 -->
          <el-table :data="userlist" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                  <!-- 作用域插槽来获取状态的true和false -->
                  <template slot-scope="scope">
                    <!-- 状态开关 -->
                    <el-switch
                          v-model="scope.row.mg_state" @change="userchange(scope.row)"
                         >
                    </el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="190px">
                        <template slot-scope="scope">
                                <!-- 修改按钮 -->
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row.id)"></el-button>
                                <!-- 删除按钮 -->
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delmove(scope.row.id)"></el-button>
                                <!-- 分配按钮 -->
                                <el-tooltip class="item" effect="dark" content="角色分配" placement="top" :enterable="false">
                                    <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                                </el-tooltip>  
                        </template>
                </el-table-column>
          </el-table>
            <!-- 分液器 -->
            <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="queryinfo.pagenum"
                  :page-sizes="[2, 3, 4, 6]"
                  :page-size="queryinfo.pagesize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total">
            </el-pagination>
      </el-card>
            <!-- 对话框 -->

            <el-dialog
                  title="添加用户" 
                  :visible.sync="adddialog"
                  width="50%"
                  @close="addDialog"
                  >
                  <!-- 内容主题区域 -->
                  <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="70px">
                    <el-form-item label="用户名" prop="username">
                          <el-input v-model="addFrom.username"></el-input>
                    </el-form-item>
                     <el-form-item label="密码" prop="password">
                          <el-input v-model="addFrom.password"></el-input>
                    </el-form-item>
                     <el-form-item label="邮箱" prop="email">
                          <el-input v-model="addFrom.email"></el-input>
                    </el-form-item>
                     <el-form-item label="手机" prop="mobile">
                          <el-input v-model="addFrom.mobile"></el-input>
                    </el-form-item>
                  </el-form>
                    <!-- 对话框底部区域 -->
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="adddialog = false">取消</el-button>
                    <el-button type="primary" @click="adduser" >确定</el-button>
                  </span>
            </el-dialog>

            <!-- 修改用户的对话框 -->
            <el-dialog
              title="修改用户"
              :visible.sync="Editdialog"
              width="50%"
              @close="addDialog"
              >
                <el-form :model="editfrom" :rules="addFromRules" ref="addFromRef" label-width="70px">
                      <el-form-item label="用户名">
                              <el-input v-model="editfrom.username" disabled></el-input>
                      </el-form-item>   
                      <el-form-item label="邮箱" prop="email">
                              <el-input v-model="editfrom.email"></el-input>
                      </el-form-item>  
                      <el-form-item label="手机号" prop="mobile">
                              <el-input v-model="editfrom.mobile"></el-input>
                      </el-form-item>  
                </el-form>  
              
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="Editdialog = false">取 消</el-button>
                      <el-button type="primary" @click="editinfo">确 定</el-button>
                    </span>
            </el-dialog>
            <!-- 删除弹框提示 -->
            <template>
                <el-button type="text" @click="open">点击打开 Message Box</el-button>
            </template>
           
    </div>
</template>
<script>
export default {
    name:"User",
    data(){
      // 定义邮箱规则
      var checkEmail=(rule,value,cb)=>{
          let regEmail=/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
          if(regEmail.test(value)){
            // 合法的邮箱
            return cb()
          }
          cb(new Error('请输入合法的邮箱'))
      }
      // 验证手机号的规则
      var checkMobile=(rule,value,cb)=>{
          // 验证手机号的正则
          let regMobile=/^0?1[3-9]\d{9}$/;
          if(regMobile.test(value)){
            // 合法手机号
            return cb()
          }
          cb(new Error("请输入合法手机号"))
      }
      return{
          // 获取用户列表的参数
          queryinfo:{
            query:'',
            // 当前的页数
            pagenum:1,
            // 当前每页显示多少条
            pagesize:2
          },
          userlist:[],
          total:0,
          // 控制对话框的显示和隐藏
          adddialog:false,
          // 添加表单数据
          addFrom:{
            username:'',
            password:'',
            email:'',
            mobile:''
          },
          // 表单规则验证
          addFromRules:{
          username:[
              { required: true, message: '请输入用户名', trigger: 'blur' },
              { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
          ],
          // 密码的规则验证
          password:[
              { required: true, message: '请输入密码', trigger: 'blur' },
              { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
          ],
          // 邮箱的验证规则
          email:[
              { required: true, message: '请输入邮箱', trigger: 'blur' },
              { validator:checkEmail, trigger:'blur' }
          ],
          // 手机的验证规则
          mobile:[
              { required: true, message: '请输入手机号', trigger: 'blur' },
              { validator:checkMobile, trigger:'blur' }
          ]
          },
          // 修改用户
          Editdialog:false,
          // 查询到的用户信息对象
          editfrom:{
            
          },
          // 修改表单的验证规则
          addFromRules:{
            email:[
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { validator:checkEmail, trigger:'blur' }
            ],
             mobile:[
              { required: true, message: '请输入手机号', trigger: 'blur' },
              { validator:checkMobile, trigger:'blur' }
          ]
          }

      }
    },
    mounted(){
      this.getuserlist()
    },
    methods:{
      async getuserlist(){
        let {data:res}=await this.$axios.get("users",{params:this.queryinfo})
        console.log(res)
        if(res.meta.status!==200){
          return tiis.$message.error("获取用户列表失败")
        } 
        this.userlist=res.data.users
        this.total=res.data.total
      },
      // 监听页码条数的变化
      handleSizeChange(newSize){
        // console.log(newSize)
        this.queryinfo.pagesize=newSize
        this.getuserlist()
      },
      // 监听页码
      handleCurrentChange(newpage){
        // console.log(newpage)
        this.queryinfo.pagenum=newpage
        this.getuserlist()
      },
      // 监听开关的状态
     async userchange(userinfo){
          console.log(userinfo)
         let {data:res}=await this.$axios.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
         console.log(res)
         if(res.meta.status!==200){
            userinfo.mg_state=!userinfo.mg_state
           return this.$message.error("更新用户状态失败")
         } 
         this.$message.success("用户更新成功")
      },
      // 监听添加对话框关闭事件
     addDialog(){
        this.$refs.addFromRef.resetFields()
     },
    //  点击按钮添加新用户
     adduser(){
        this.$refs.addFromRef.validate(async valid=>{
          console.log(valid)
          if(!valid) return
          // 发起添加用户的请求
         let {data:res}=await this.$axios.post("users",this.addFrom)
         console.log(res)
         if(res.meta.status!==201){
              this.$message.error("添加用户失败")
         }
          this.$message.success("添加用户成功")
          // 隐藏添加的用户对话框
          this.adddialog=false
          // 刷新列表
          this.getuserlist()
        })
     },
    //  修改按钮
    async edit(id){
     let {data:res}=await this.$axios.get(`users/`+id)
     console.log(res)
     if(res.meta.status!==200){
       return this.$message.error("查询信息失败")
     } 
      this.editfrom=res.data

      this.Editdialog=true
    },
    // 修改用户对话框的关闭事件
    addDialog(){
      this.$refs.addFromRef.resetFields()
    },
    // 修改并提交用户信息
    editinfo(){
      this.$refs.addFromRef.validate(async valid=>{
        console.log(valid)
        if(!valid) return
        // 发起用户修改的请求
          const {data:res}=await this.$axios.put("users/"+this.editfrom.id,{email:this.editfrom.email,
          mobile:this.editfrom.mobile})
            if(res.meta.status!==200){
              return this.$message.error("更新用户失败")
            } 
            // 关闭对话框
            this.Editdialog=false
            // 刷新数据列表
            this.getuserlist()
            // 提示
            this.$message.success("用户修改成功")
      })
    },
    // 根据ID删除对应的值
   async delmove(id){
      console.log(id)
        // 弹框是否删除
      let confirm=await this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
          
        
        // 如果用户确认删除返回值是confirm
         // 如果用户取消删除返回值是cancel
        console.log(confirm)
        if(confirm!=="confirm"){
          return this.$message.info("用户取消删除")
        }
      let{data:res}=await this.$axios.delete(`users/`+id)
        console.log("确认了删除")
        if(res.meta.status!==200){
          return this.$message.error("删除失败")
        }
        this.$message.success("删除成功")
        this.getuserlist()
    },



    }
}
</script>
<style lang="scss" scoped>
body,h1,h2,h3,h4,h5,h6,p{
  margin: 0;
  padding: 0;
  list-style: none;
}
body,html,#app {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}  
.el-breadcrumb{
  margin-bottom: 15px;
  font-size: 12px;
}
.el-card{
  box-shadow: 0 1px 1px rgba(0,0,0,0.15);
}
.el-table{
  margin-top: 15px;
  font-size: 12px;
}
</style>